class AdminController < ApplicationController
  
  before_filter :authorize_show, :only => [ :approved_requests, :unapproved_requests, :create_new_supplier]
  before_filter :authorize_show_new_admin, :only => [:new_admin, :create_new_admin]
  
  autocomplete :part, :name, :full => true
  
  def index
    @requests = Request.find(:all, :order => :created_at)
  end
  
  def unapproved_requests
    @requests = Request.where(:is_authorized => false)  
  end
  
  def approved_requests
    @requests = Request.where(:is_authorized => true)  
  end 
  
  def create_new_supplier
    @supplier = Supplier.new  
  end
  
  def new_admin
    @admin_user = AdminUser.new  
  end 
  
  def create_new_admin
    @admin_user = AdminUser.new(params[:admin_user])

    respond_to do |format|
      if @admin_user.save
        format.html { redirect_to(admin_path, :notice => 'Supplier was successfully created.') }
      else
        format.html { redirect_to(:back, :notice => 'be ima nekfi greshki') }
      end
    end    
  end 
  
  def update_request_part_configuration
    @part_configuration = PartConfiguration.find(params[:part_configuration][:id])

    respond_to do |format|
      if @part_configuration.update_attributes(params[:part_configuration])
        format.html { redirect_to :back }
      else
        format.html { redirect_to :back, :notice => 'PartConfiguration error.' }
      end
    end
  end
  
  def delete_part_configuration
    @part_configuration = PartConfiguration.find(params[:id])
    @part_configuration.destroy

    respond_to do |format|
      format.html { redirect_to :back }
    end
  end
  
  def edit_request
    @request = Request.find(params[:id])
  end
  
  def update_request
    @request = Request.find(params[:request][:id])
    
    @request.region_requests.clear
    if !params[:request][:region_ids].nil?
      params[:request][:region_ids].each do |i|
        @request.region_requests.build(:region_id => i)
      end
    end    

    respond_to do |format|
      if @request.update_attributes(params[:request])
        format.html { redirect_to :back }
      else
        format.html { redirect_to :back, :notice => 'Request error.' }
      end
    end    
  end 
  
  def login
    
  end  
  
  def do_login
    user = AdminUser.authenticate(params[:email], params[:password])
    if user
      session[:admin_user_id] = user.id
      redirect_to admin_path
    else
      flash.now.alert = "Invalid email or password"
      render "login"
    end    
  end
  
  def logout
    session[:admin_user_id] = nil
    redirect_to admin_path
  end
  
  private
    def authorize_show
      if current_admin.nil?
        redirect_to admin_login_path
      end
    end
    
    def authorize_show_new_admin
      if (AdminUser.all.size > 0) && (current_admin.nil?) 
        redirect_to admin_login_path
      end
    end    

end
